import { ref, markRaw, onMounted, watch } from 'vue';
import { GetTaskDataSummaryListParams } from '@/apis/eci/carbonManagement/model/dataListModel';
import { getTaskDataSummaryList } from '@/apis/eci/carbonManagement/dataList';
import { thousandFormat, transformUnitKgToT } from '@/utils';
import {
  SearchOptionsType,
  ColumnSettingTypeEnum,
  TableFieldsSettingType
} from '@/components/CPageTable';
import { useRoute } from 'vue-router';

export const useList = (props: any) => {
  const route = useRoute();
  const dataSource = ref<any[]>([]);
  const loading = ref(false);
  // 页面标题
  const taskNo = route.query.taskNo as any;
  // 搜索配置
  const searchOptions: SearchOptionsType[] = markRaw([]);
  let spanEmissionScope: any[] = [];
  let spanEmissionCategory: any[] = [];
  let spanGhgSourceType: any[] = [];

  const posSpanEmissionScope = ref(0); // 范围
  const posSpanEmissionCategory = ref(0); // 排放类别
  const posGhgSourceType = ref(0); // 温室气体类型
  const getSpanArr = (data: any) => {
    for (let i = 0; i < data.length; i++) {
      if (i === 0) {
        spanEmissionScope.push(1);
        posSpanEmissionScope.value = 0;
      } else {
        // 判断当前元素与上一个元素是否相同
        if (data[i].emissionScope === data[i - 1].emissionScope) {
          spanEmissionScope[posSpanEmissionScope.value] += 1;
          spanEmissionScope.push(0);
        } else {
          spanEmissionScope.push(1);
          posSpanEmissionScope.value = i;
        }
      }

      if (i === 0) {
        spanEmissionCategory.push(1);
        posSpanEmissionCategory.value = 0;
      } else {
        // 判断当前元素与上一个元素是否相同
        if (
          data[i].emissionCategory === data[i - 1].emissionCategory &&
          data[i].emissionScope === data[i - 1].emissionScope
        ) {
          spanEmissionCategory[posSpanEmissionCategory.value] += 1;
          spanEmissionCategory.push(0);
        } else {
          spanEmissionCategory.push(1);
          posSpanEmissionCategory.value = i;
        }
      }

      if (i === 0) {
        spanGhgSourceType.push(1);
        posSpanEmissionCategory.value = 0;
      } else {
        // 判断当前元素与上一个元素是否相同
        if (
          data[i].ghgSourceName === data[i - 1].ghgSourceName &&
          data[i].emissionCategory === data[i - 1].emissionCategory
        ) {
          spanGhgSourceType[posGhgSourceType.value] += 1;
          spanGhgSourceType.push(0);
        } else {
          spanGhgSourceType.push(1);
          posGhgSourceType.value = i;
        }
      }
    }
  };
  const cellMerge = ({ rowIndex, columnIndex }: any) => {
    if (columnIndex === 0) {
      const _row = spanEmissionScope[rowIndex];
      const _col = _row > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col
      };
    }
    if (columnIndex === 1) {
      const _row = spanEmissionCategory[rowIndex];
      const _col = _row > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col
      };
    }
    if (columnIndex === 2) {
      const _row = spanGhgSourceType[rowIndex];
      const _col = _row > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col
      };
    }
  };

  const tableFieldsSetting: TableFieldsSettingType[] = [
    {
      title: '因子编号',
      field: 'factorNo',
      width: 230,
      fixed: 'left',
      columnSettingConfig: {
        enabled: true,
        type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '因子名称',
      field: 'factorName',
      minWidth: 300,
      columnSettingConfig: {
        enabled: true
        // type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '类别',
      field: 'category',
      slot: 'categorySlot',
      width: 120,
      columnSettingConfig: {
        enabled: true
        // type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '排放因子',
      field: 'emissionFactor',
      headerSlot: 'emissionFactorHeaderSlot',
      width: 120,
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '单位',
      field: 'factorUnit',
      width: 120,
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '国别',
      field: 'country',
      width: 80,
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '基准年',
      field: 'baseYear',
      width: 80,
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '来源类型',
      field: 'factorCreateType',
      slot: 'factorCreateTypeSlot',
      width: 100,
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '因子来源',
      field: 'factorSource',
      slot: 'factorSourceSlot',
      width: 100,
      columnSettingConfig: {
        enabled: true
        // type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '因子状态',
      field: 'status',
      slot: 'statusSlot',
      width: 120,
      columnSettingConfig: {
        enabled: true
        // type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '发布日期',
      field: 'releaseDate',
      width: 120,
      columnSettingConfig: {
        enabled: true
        // type: ColumnSettingTypeEnum.REQUIRED
      }
    },
    {
      title: '操作',
      field: 'op',
      slot: 'op',
      width: 100,
      fixed: 'right',
      columnSettingConfig: {
        enabled: true,
        type: ColumnSettingTypeEnum.FIXED
      }
    }
  ];
  onMounted(() => {
    loadData();
  });
  function loadData() {
    const params: GetTaskDataSummaryListParams = {
      taskNo,
      standard: props.standard
    };
    loading.value = true;
    getTaskDataSummaryList(params)
      .then((res: any) => {
        if (res) {
          spanEmissionScope = [];
          spanEmissionCategory = [];
          spanGhgSourceType = [];
          posSpanEmissionScope.value = 0;
          posSpanEmissionCategory.value = 0;
          posGhgSourceType.value = 0;
          getSpanArr(res);
          dataSource.value = res;
        } else {
          dataSource.value = [];
        }
        loading.value = false;
      })
      .catch(error => {
        console.log('error', error);
        loading.value = false;
        dataSource.value = [];
      });
  }

  const mergeCells = ref([{ row: 0, col: 3, rowspan: 1, colspan: 3 }]);
  const sumNum = (list: any[], field: string) => {
    let count = 0;
    list.forEach(item => {
      count += Number(item[field]);
    });
    return thousandFormat(transformUnitKgToT(count, 5));
  };
  const footerMethod = ({ columns, data }: any) => {
    if (!dataSource.value.length) return new Array(columns.length);
    const footerData = [
      columns.map((column: any, _columnIndex: number) => {
        if (_columnIndex === 0) {
          return '绝对排放量';
        }
        if (['proportion'].includes(column.field)) {
          return '100';
        }
        if (['totalEmission'].includes(column.field)) {
          return sumNum(data, column.field);
        }
        return null;
      })
    ];
    return footerData;
  };
  const extraTableOption = {
    spanMethod: cellMerge,
    mergeFooterItem: mergeCells.value,
    footerMethod: footerMethod,
    showFooter: true,
    maxHeight: '490'
  };
  return {
    // 头部右侧筛选项配置
    searchOptions,
    // 筛选项字段
    tableFieldsSetting,
    loadData,
    dataSource,
    loading,
    extraTableOption
  };
};
